/**
 * Created by Administrator on 2017/6/19.
 */
/**
 * Created by Administrator on 2017/6/12.
 */
var Promise = require('bluebird');
var User = Promise.promisifyAll(require('../models/user'));

//user列表页
exports.list = function *(req, res) {
  var _users = yield User.findAll();
  res.render('user/userList', {
    title: 'user列表页',
    users: _users
  });
}

//user注册页
exports.signup = function *(req, res) {
  res.render('user/userSignup', {
    title: 'user注册页'
  });
}

//user登录页
exports.signin = function *(req, res) {
  res.render('user/userSignin', {
    title: 'user登录页'
  });
}

//user进行注册
exports.create = function *(req, res) {
  var user = req.body;
  user.role = 0;
  user.time = Date.now();
  //先查询用户是否存在
  var _user = yield User.findOne({name: user.name});
  if (_user) {
    res.send('用户已存在!');
  } else {
    var newUser = new User(user);
    yield newUser.save();
    res.redirect('/user/signin');
  }
}

//user进行登录
exports.login = function *(req, res) {
  var user = req.body;
  var _user = yield User.findOne({name: user.name, password: user.password});
  var result = {};
  if (_user) {
    req.session.user = _user;
    if (user.remember == 'true') {
      req.session.cookie.originalMaxAge = 1000 * 60 * 60 * 24 * 14;
    }
    result.status = 'true';
    result.msg = '登录成功';
    if (req.session.url) {
      result.url = req.session.url;
    } else {
      result.url = '/';
    }
  } else {
    result.status = 'false';
    result.msg = '用户名或密码错误';
  }
  res.json(result);
}

//user进行登出
exports.logout = function *(req, res) {
  delete req.session.user;
  delete req.session.url;
  req.session.cookie.originalMaxAge = -1;
  res.redirect('/');
}

//user进行删除
exports.del = function *(req, res) {
  var id = req.body.id;
  var commandResult = yield User.remove({_id: id});
  if (commandResult.result.n == 1) {
    res.send('true');
  } else {
    res.send('false');
  }
}

//user进行修改
exports.update = function *(req, res) {
  var user = req.body;
  var doc = yield User.update({_id: user.id}, {password: user.password});
  if (doc.nModified == 1) {
    res.redirect('/');
  }
}

//superAdmin权限控制
exports.superAdminPermission = function (req, res, next) {
  if (req.session.user && req.session.user.role == 2) {
    next();
  } else {
    res.render('common/permission');
  }
}

//admin权限控制
exports.adminPermission = function (req, res, next) {
  if (req.session.user && req.session.user.role >= 1) {
    next();
  } else {
    res.render('common/permission');
  }
}

//login控制
exports.loginPermission = function (req, res, next) {
  if (req.session.user) {
    next();
  } else {
    req.session.url = req.url;
    res.redirect('/user/signin');
  }
}